package nc.gk.gkxm.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import nc.gk.gkxm.exception.LoginFailedException;
import nc.gk.gkxm.mapper.UserMapper;
import nc.gk.gkxm.model.dto.UserLoginDto;
import nc.gk.gkxm.model.entity.User;
import nc.gk.gkxm.model.other.WeChatProperties;
import nc.gk.gkxm.service.UserService;
import nc.gk.gkxm.utils.jwt.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    public static final String WxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    /**
     * 微信登录
     * @param userLoginDto
     * @return
     */
    @Override
    public User login(UserLoginDto userLoginDto) {
        //请求微信服务器获取openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDto.getCode());
        map.put("grant_type","authorization_code");
//        String json = HttpClientUtil.doGet(WxLoginUrl, map);
        String json = "{\"session_key\":\"LAdWyHDqG+AvxeRp9FKwkQ==\",\"openid\":\"on-zq4iZ1CLhpWO-JBc1hvrsA7w4\"}";
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        //检查openid是否为空
        if (openid == null){
            throw new LoginFailedException("登录失败");
        }
        //判断是否为新用户（自动注册）
        User user = userMapper.getUserByOpenId(openid);
        if (user == null){
            user = new User();
            user.setAppid(openid);
            user.setCreatetime(new Date());
            userMapper.insert(user);
        }
        //返回用户对象
        return user;
    }
}